const express = require('express');
const app = express();
const router = express.Router();
const CommodityController = require('../../controllers/commodity/commodity.controller');
const fs = require('fs');
const formidable = require('formidable');

// 上传图片路由
let uploadPath = '';
router.post('/upload', async (req, res, next) => {
    const form = new formidable.IncomingForm({
        multiple: true,
        // 上传文件得保存目录
        uploadDir: __dirname + '/../../../public/images',
        // 保留文件扩展名
        keepExtensions: true,
    })

    await form.parse(req, (err, fields, files) => {
        if (err) {
            next(err);
            return;
        }
        uploadPath = '/images/' + files.file[0].newFilename; // 将次数据保存到数据库中

    })
    res.send({
        code: 200,
        msg: '上传成功',
        data: uploadPath
    })
})

// 添加商品路由
router.post("/create", (req, res, next) => {
    CommodityController.CreateCommodity({
        title: req.body.title,
        price: req.body.price,
        detail: req.body.detail,
        type: req.body.type,
        date: req.body.date,
        uploadPath: uploadPath
    }).then(data => {
        res.send({
            code: 106,
            message: '添加成功',
            data: data
        })
    }).catch(err => {
        res.send({
            code: 206,
            message: '添加失败',
            data: err
        })
    })
})

// 查询所有数据的接口
router.get('/find', CommodityController.findAll)

// 删除商品接口
router.delete('/delete', CommodityController.delete)

// 修改商品接口
router.patch('/update', CommodityController.update)

module.exports = router;